package com.beidouapp.common.util;

import net.sf.json.JSONObject;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpEntityEnclosingRequestBase;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import java.util.HashMap;
import java.util.Map;


/**
 * @author LAOT
 *适用不同的业务需求添加到service实现工具包
 *
 */
public class APIHttpClient
{

	private static Log logger = LogFactory.getLog(APIHttpClient.class);

	/**
	 * @Title:Http请求公共方法
	 * @Description:
	 * @param method
	 *            参数代表HttpEntity请求示例 如 HttpPost、HttpPut
	 * @param paraJson
	 *            代表传输的json格式的参数
	 * @return 返回值为json
	 */
	@SuppressWarnings({ "deprecation", "unused" })
	public static JSONObject sendHttpPostOrPutRequest(HttpEntityEnclosingRequestBase method, JSONObject paraJson)
	{

		long startTime = 0L;
		long endTime = 0L;
		int status = 0;// 0.成功 1.执行方法失败 2.协议错误 3.网络错误
		JSONObject resultJsonObject = null;
		logger.info("json:" + paraJson.toString());
		HttpClient httpClient = new DefaultHttpClient();
		try
		{
			StringEntity entity = null;
			if (null != paraJson)
			{
				entity = new StringEntity(paraJson.toString(), "utf-8");// 解决中文乱码问题
			}
			else
			{
				entity = new StringEntity("", "utf-8");
			}
			entity.setContentEncoding("UTF-8");
			entity.setContentType("application/json");
			method.addHeader("Content-Type", "application/json");
			method.setEntity(entity);
			startTime = System.currentTimeMillis();
			// 设置编码
			HttpResponse response = httpClient.execute(method);
			endTime = System.currentTimeMillis();
			int statusCode = response.getStatusLine().getStatusCode();
			logger.info("statusCode:" + statusCode);
			logger.info("调用API 花费时间(单位：毫秒)：" + (endTime - startTime));
			if (statusCode != HttpStatus.SC_OK)
			{
				logger.error("Method failed:" + response.getStatusLine());
				status = 1;
			}
			HttpEntity httpEntity = response.getEntity();
			// Read the response body
			if (httpEntity != null)
			{
				String body = EntityUtils.toString(httpEntity, "UTF-8");
				System.out.println(body);
				resultJsonObject = JSONObject.fromObject(body);
				logger.info("解析返回的参数： " + resultJsonObject);
				/*
				 * try { bufferedReader = new BufferedReader(new InputStreamReader(httpEntity.getContent(), "UTF-8"), 8
				 * * 1024); String line = null; while((line = bufferedReader.readLine()) != null) {
				 * entityStringBuilder.append(line + "/n"); } // 利用从HttpEntity中得到的String生成JsonObject resultJsonObject =
				 * JSONArray.fromObject(entityStringBuilder); } catch (Exception e) { e.printStackTrace(); }
				 */
			}
			else
			{
				throw new Exception("程序发生异常，没有响应！");
			}

		}
		catch (Exception e)
		{
			// 发生网络异常
			logger.error("exception occurred!\n" + ExceptionUtils.getFullStackTrace(e));
			// 网络错误
			status = 3;
			resultJsonObject.put("errorcode ", 100);
			resultJsonObject.put("message", TimingStatus.getErrorMsg(100));
			resultJsonObject.put("exception", e.getMessage());
			return resultJsonObject;
		}
		finally
		{

			logger.info("调用接口状态：" + status);
		}
		return resultJsonObject;
	}

	
	/**  
	* @Title: 支持HttpRequestBase子类(HttpGet、HttpDelete无参请求)
	* @Description: TODO
	*/ 
	@SuppressWarnings("resource")
	public static JSONObject sendHttpGetOrDeleteRequest(HttpRequestBase method)
	{
		long startTime = 0L;
		long endTime = 0L;
		int status = 0;// 0.成功 1.执行方法失败 2.协议错误 3.网络错误
		JSONObject resultJsonObject = null;
		HttpClient httpClient = new DefaultHttpClient();
		try
		{
			startTime = System.currentTimeMillis();
			// 配置请求的超时设置
			RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(50).setConnectTimeout(50)
					.setSocketTimeout(50).build();
			method.setConfig(requestConfig);

			// 设置编码
			HttpResponse response = httpClient.execute(method);
			endTime = System.currentTimeMillis();
			int statusCode = response.getStatusLine().getStatusCode();
			logger.info("statusCode:" + statusCode);
			logger.info("调用API 花费时间(单位：毫秒)：" + (endTime - startTime));
			if (statusCode != HttpStatus.SC_OK)
			{
				logger.error("Method failed:" + response.getStatusLine());
				status = 1;
			}
			HttpEntity httpEntity = response.getEntity();
			// Read the response body
			if (httpEntity != null)
			{
				String body = EntityUtils.toString(httpEntity, "UTF-8");
				System.out.println(body);
				resultJsonObject = JSONObject.fromObject(body);
				logger.info("解析返回的参数： " + resultJsonObject);
			}
			else
			{
				throw new Exception("程序发生异常，没有响应！");
			}

		}
		catch (Exception e)
		{
			// 发生网络异常
			logger.error("exception occurred!\n" + ExceptionUtils.getFullStackTrace(e));
			// 网络错误
			status = 3;
			resultJsonObject=new JSONObject();
			resultJsonObject.put("errorcode ", 100);
			resultJsonObject.put("message", TimingStatus.getErrorMsg(100));
			resultJsonObject.put("exception", e.getMessage());
			return resultJsonObject;
		}
		finally
		{

			logger.info("调用接口状态：" + status);
			method.releaseConnection();
		}
		return resultJsonObject;
	}

	public static void main(String[] args)
	{
		
		JSONObject responsJson=new JSONObject();
		JSONObject jsonPara = new JSONObject();
		Map<String, Object> info = new HashMap<String, Object>();
		info.put("topic","特情发布示例");
		info.put("senderRole","111");
		info.put("contents","特情发布啦！");
		info.put("level","1");
		info.put("flight","A343D3");
		info.put("receiveIds",new String[]{"d89f815a1d914fc498e723bfd82922e1"});
		/**
		 * 调用示例如下
		 * */
		jsonPara=JSONObject.fromObject(info);
		HttpPost httpPost=new HttpPost("http://localhost:9090/specialSituation/pushSpecialSituations");
		responsJson=APIHttpClient.sendHttpPostOrPutRequest(httpPost, jsonPara);
		System.out.println(responsJson);
	}
}
